package cn.tedu._05weibo.common.exception;

import cn.tedu._05weibo.common.response.JsonResult;
import cn.tedu._05weibo.common.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * ExceptionHandler注解:标识此方法异常处理方法
     */
    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex) {
        /*
        ex.getMessage()方法：获取异常提示消息；
         */
        log.error("IllegalArgumentException=" + ex.getMessage());
        return new JsonResult(StatusCode.OPERATION_FAILED, ex.getMessage());
    }

//    @ExceptionHandler
//    public JsonResult doHandleRuntimeException(RuntimeException ex) {
//        log.error("RuntimeException=" + ex.getMessage());
//        return new JsonResult(StatusCode.OPERATION_FAILED, ex.getMessage());
//    }

    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        /*
        DTO类方式校验:获取提示消息使用:getFieldError().getDefaultMessage();
         */
        String message=ex.getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidException="+message);
        return new JsonResult(StatusCode.VALIDATED_ERROR,message);
    }
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
        String message=ex.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException="+message);
        return new JsonResult(StatusCode.VALIDATED_ERROR,message);
    }

//    @ExceptionHandler
//    public JsonResult doHandleThrowable(Throwable ex) {
//        log.error("Throwable=" + ex.getMessage());
//        return new JsonResult(StatusCode.THROWABLE_ERROR,ex.getMessage());
//    }
}
